<?php

defined('SYSPATH') or die('Access error!');

class CSRF
{

   /**
    * 设置token
    * @return type
    */
    public static function set_csrf_token()
    {
        $token = md5(Request::$user_agent . Session::instance()->id() . self::_private_key());
        self::delete_token();
        Session::instance()->set('token', $token);
        return $token;
    }

  /*
   * 获取token
   */
    public static function get_csrf_token()
    {
        if (($token = Session::instance()->get('token', NULL)))
            return $token;
    }

    /**
     *  检查token
     * @param type $token
     * @param type $redirect_page
     * @return boolean
     */
    public static function check_csrf_token($token = '', $redirect_page = NULL)
    {
        if (self::get_csrf_token() === $token)
        {
            self::delete_token();
            return TRUE;
        }



        return FALSE;
    }

    /**
     *  生成唯一的key
     * @return string
     */
    private static function _private_key()
    {
        $key = sha1(uniqid(mt_rand(), true)) . md5(uniqid(mt_rand(), true));
        return $key;
    }

    /**
     * 删除token
     */
    public static function delete_token()
    {
        Session::instance()->delete('token');
    }

}